﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace NET.Library.XML.Linq
{
    /// <summary>
    /// Helper object for working with Xml Linq objects.
    /// </summary>
    public class XDocumentHelper
    {
        ///----------------------------------------------------------------------------------
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentElement"></param>
        /// <param name="xmlElementPaths"></param>
        /// <param name="xmlAttributeName"></param>
        /// <returns></returns>
        ///----------------------------------------------------------------------------------
        public static string GetValue(XElement parentElement, string[] xmlElementPaths, string xmlAttributeName)
        {
            foreach (string path in xmlElementPaths)
            {
                string value = GetValue(parentElement, path, xmlAttributeName);
                if (value.Trim() != "")
                    return value;
            }
            return "";
        }

        ///----------------------------------------------------------------------------------
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentElement"></param>
        /// <param name="xmlElementPath"></param>
        /// <param name="xmlAttributeName"></param>
        /// <returns></returns>
        ///----------------------------------------------------------------------------------
        public static string GetValue(XElement parentElement, string xmlElementPath, string xmlAttributeName)
        {
            string[] elementNames = xmlElementPath.Split('/');
            XElement element = parentElement;

            foreach (string name in elementNames.Where(n => n != ""))
            {
                element = element.Element(name);
                if (element == null)
                {
                    return "";
                }
            }

            if (string.IsNullOrEmpty(xmlAttributeName))
            {
                return element.Value;
            }

            XAttribute attr = element.Attribute(xmlAttributeName);
            if (attr == null)
            {
                return "";
            }
            return attr.Value;
        }
    }
}
